package com.wish.group05.base.service.impl;

import com.wish.group05.base.entity.MSequence;
import com.wish.group05.base.mapper.MSequenceMapper;
import com.wish.group05.base.service.IMSequenceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.group05.common.core.utils.SpringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * <p>
 * 序号表（取编号用） 服务实现类
 * </p>
 *
 * @author houzehui
 * @since 2022-05-23
 */
@Service
public class MSequenceServiceImpl extends ServiceImpl<MSequenceMapper, MSequence> implements IMSequenceService {

    /**
     * @Description: 生成编号
     * @param tpye 编号类型
     * @return 生成的编号
     */
    @Override
    public String getSerialNumber(String type) throws Exception {
        try {
            TransactionStatus beginTransaction = this.beginTransaction(3);
            String result = getBaseMapper().getSerialNumber(type);
            this.commit(beginTransaction);
            if(!StringUtils.isNotBlank(result)) {
                throw new Exception("未获取到编号");
            }
            int random = (int) ((Math.random()*9+1)*1000);
            result = type + result + random;
            return result;
        } catch (Exception e) {
            throw e;
        }
    }

    protected void commit(TransactionStatus status) {
        getTransactionMgr().commit(status);
    }

    private DataSourceTransactionManager transactionMgr;
    protected DataSourceTransactionManager getTransactionMgr() {
        if (transactionMgr == null) {
            transactionMgr = SpringUtils.getBean(DataSourceTransactionManager.class);
        }
        return transactionMgr;
    }

    protected TransactionStatus beginTransaction(int propagationBehavior) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(propagationBehavior);
        return getTransactionMgr().getTransaction(def);
    }

}
